In Svelte, you can listen to any standard DOM event using the on:eventName directive. This works for all built-in browser events like clicks, keyboard input, form submissions, and more. It is similar to using addEventListener in plain JavaScript, but with simpler syntax.
Mouse Events: on:click, on:dblclick, on:mouseenter, on:mouseleave, on:mousemove
Keyboard Events: on:keydown, on:keyup, on:keypress
Form Events: on:submit, on:input, on:change, on:focus, on:blur
Touch Events: on:touchstart, on:touchmove, on:touchend
Clipboard Events: on:copy, on:paste, on:cut
Drag and Drop Events: on:dragstart, on:dragover, on:drop
Window/Document Events: on:scroll, on:resize (when used on window)
Here, the on:click directive listens for a click event on the button and runs the handleClick function whenever the button is pressed.
This example captures keyboard input and displays the most recently pressed key.
The special <svelte:window> element allows you to listen to events that happen on the global window object, such as resize or scroll.
Svelte supports all native DOM events using the on:eventName directive.
You can use events on any HTML element or special Svelte elements like <svelte:window> and <svelte:document>.
Event objects are automatically passed to the handler function as the first argument.
No manual cleanup is needed — Svelte automatically removes event listeners when components are destroyed.